<?php

namespace Sdk\Plglobal;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use L;
//use of_base_com_kv;

class callPlglobalApiUtil
{
    private const URL = "https://3plglobal.gigacloudlogistics.com";

    private const USER_NAME = "D381";
    private const USER_PASSWORD = "D381@2589";
    private const SECRET = '602d483f222b4471f4421251c47cb0ad';

    public static function callPlglobalApi($action, $method, $data)
    {
        try {
            $client = new Client();
            $url = self::URL . $action;
            $headers = [
                'Content-Type' => 'application/json',
                'chraset' => 'UTF-8'
            ];
            if ('/3plapi/getToken' != $action) {
                //header签名
                $token = json_decode(self::token(), true)['token'];
                $date = date('Y-m-d H:i:s');
                $headers = array_merge($headers, [
                    'Authorization' => $token,
                    'x-timestamp' => $date,
                    'x-sign' => strtolower(md5($token.$date.self::SECRET))
                ]);

                $param = [
                    'timestamp' => date('Y-m-d H:i:s')
                ];
                if (!empty($data)) {
                    $data = array_merge($param, $data);
                } else {
                    $data = $param;
                }
            } else {
                $auth = [
                    'username' => self::USER_NAME,
                    'password' => self::USER_PASSWORD,
                ];
                if (!empty($data)) {
                    $data = array_merge($auth, $data);
                } else {
                    $data = $auth;
                }
            }
            if ('post' == strtolower($method)) {
                $response = $client->request($method, $url, ['headers' => $headers, 'json' => $data]);
            } else {
                $queryString  = http_build_query($data);
                $url .= '?'.$queryString;
                $response = $client->request($method, $url, ['headers' => $headers]);
            }
            $status = $response->getStatusCode();
            if (200 == $status) {
                $result = $response->getBody()->getContents();
                return json_decode($result, true);
            } else {
                return [];
            }
        } catch (ClientException $e) {
            return [];
        }
    }

    //获取存储在Redis中的token
    private static function token()
    {
        //$token = of_base_com_kv::link('default')->get('plglobal');
        $sql = "SELECT * FROM token WHERE 1 AND `type` = 'plglobal';";
        $result = L::sql($sql);
        return !empty($result) ? $result[0]['data'] : '';
    }

}